package io.renren.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

public class OSSUtil {
	public static String accessKeyId = "GYTtYsrII7SOvyUh";
	public static String accessKeySecret = "9XImeA7TuK7Lovpsy5XLpY5SKPk7d9";

	/**
	 * 阿里云OSS_ENDPOINT 青岛Url
	 */
	public static String OSS_ENDPOINT = "http://oss-cn-qingdao.aliyuncs.com";
	/**
	 * 阿里云BUCKET_NAME OSS
	 */
	public static String BUCKET_NAME = "nocimg";
	public static OSSClient client = new OSSClient(OSSUtil.OSS_ENDPOINT, OSSUtil.accessKeyId, OSSUtil.accessKeySecret);
	public static String FILE_DIR = "jnmtemall";

	/**
	 * 创建Bucket
	 * 
	 * @param client
	 *            OSSClient对象
	 * @param bucketName
	 *            BUCKET名
	 * @throws OSSException
	 * @throws ClientException
	 */
	public static void ensureBucket(OSSClient client, String bucketName) throws OSSException, ClientException {
		try {
			// 获取用户的Bucket列表
			List<Bucket> buckets = client.listBuckets();

			// 遍历Bucket
			for (Bucket bucket : buckets) {
				System.out.println(bucket.getName());
			}
			// 获取Bucket的存在信息
			boolean exists = client.doesBucketExist(bucketName);
			if (!exists) {
				client.createBucket(bucketName);
				OSSUtil.setBucketPublicReadable(client, OSSUtil.BUCKET_NAME);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除一个Bucket和其中的Objects
	 * 
	 * @param client
	 *            OSSClient对象
	 * @param bucketName
	 *            Bucket名
	 * @throws OSSException
	 * @throws ClientException
	 */
	public static void deleteBucket(OSSClient client, String bucketName) throws OSSException, ClientException {
		ObjectListing ObjectListing = client.listObjects(bucketName);
		List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
		for (int i = 0; i < listDeletes.size(); i++) {
			String objectName = listDeletes.get(i).getKey();
			System.out.println("objectName = " + objectName);
			// 如果不为空，先删除bucket下的文件
			client.deleteObject(bucketName, objectName);
		}
		client.deleteBucket(bucketName);
	}

	/**
	 * 把Bucket设置成所有人可读
	 * 
	 * @param client
	 *            OSSClient对象
	 * @param bucketName
	 *            Bucket名
	 * @throws OSSException
	 * @throws ClientException
	 */
	public static void setBucketPublicReadable(OSSClient client, String bucketName)
			throws OSSException, ClientException {
		// 创建bucket
		client.createBucket(bucketName);
		// 设置bucket的访问权限， public-read-write权限
		client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
	}

	/**
	 * 上传文件
	 * 
	 * @param Objectkey
	 *            上传到OSS起的名
	 * @param uploadfile
	 *            本地文件名
	 * @throws OSSException
	 * @throws ClientException
	 * @throws FileNotFoundException
	 */
	public static void uploadFile(String Objectkey, File uploadfile)
			throws OSSException, ClientException, FileNotFoundException {
		File file = uploadfile;
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(file.length());
		// 判断上传类型，多的可根据自己需求来判定
		if (file.getName().endsWith("xml")) {
			objectMeta.setContentType("text/xml");
		} else if (file.getName().endsWith("jpg") || file.getName().endsWith("jpeg")) {
			objectMeta.setContentType("image/jpeg");
		} else if (file.getName().endsWith("png")) {
			objectMeta.setContentType("image/png");
		} else if (file.getName().endsWith("gif")) {
			objectMeta.setContentType("image/gif");
		}
		Objectkey = FILE_DIR + "/" + Objectkey;
		InputStream input = new FileInputStream(file);
		client.putObject(BUCKET_NAME, Objectkey, input, objectMeta);
	}

	public static void uploadFile(String Objectkey, InputStream inputStream, Long length)
			throws OSSException, ClientException, FileNotFoundException {
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(length);
		// 判断上传类型，多的可根据自己需求来判定
		if (Objectkey.endsWith("xml")) {
			objectMeta.setContentType("text/xml");
		} else if (Objectkey.endsWith("jpg") || Objectkey.endsWith("jpeg")) {
			objectMeta.setContentType("image/jpeg");
		} else if (Objectkey.endsWith("png")) {
			objectMeta.setContentType("image/png");
		} else if (Objectkey.endsWith("gif")) {
			objectMeta.setContentType("image/gif");
		}
		Objectkey = FILE_DIR + "/" + Objectkey;
		client.putObject(BUCKET_NAME, Objectkey, inputStream, objectMeta);
	}

	/**
	 * 下载文件
	 * 
	 * @param client
	 *            OSSClient对象
	 * @param bucketName
	 *            Bucket名
	 * @param Objectkey
	 *            上传到OSS起的名
	 * @param filename
	 *            文件下载到本地保存的路径
	 * @throws OSSException
	 * @throws ClientException
	 */
	public static void downloadFile(OSSClient client, String bucketName, String Objectkey, String filename)
			throws OSSException, ClientException {
		client.getObject(new GetObjectRequest(bucketName, Objectkey), new File(filename));
	}

	public static URL getUrl(OSSClient client, String bucketName, String Objectkey) {
		// 设置URL过期时间为1小时
		Date expiration = new Date(new Date().getTime() + 3600 * 1000);
		// 生成URL
		URL url = client.generatePresignedUrl(bucketName, Objectkey, expiration);
		return url;
	}

}
